/**
 * Alipay.com Inc.
 * Copyright (c) 2004-2014 All Rights Reserved.
 */
package com.alipay.executor;

import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayOpenPublicMessageCustomSendRequest;
import com.alipay.api.response.AlipayOpenPublicMessageCustomSendResponse;
import com.alipay.factory.AlipayAPIClientFactory;
import com.alipay.util.AlipayMsgBuildUtil;

import net.sf.json.JSONObject;

/**
 * 关注服务窗执行器
 * 
 * @author baoxing.gbx
 * @version $Id: InAlipayFollowExecutor.java, v 0.1 Jul 24, 2014 4:29:04 PM baoxing.gbx Exp $
 */
public class InAlipayFollowExecutor implements ActionExecutor {

    /** 业务参数 */
    private JSONObject bizContent;

    public InAlipayFollowExecutor(JSONObject bizContent) {
        this.bizContent = bizContent;
    }

    public InAlipayFollowExecutor() {
        super();
    }

    @Override
    public String execute() {

        //TODO 根据支付宝请求参数，可以将支付宝账户UID-服务窗ID关系持久化，用于后续开发者自己的其他操作
        // 这里只是个样例程序，所以这步省略。
        // 直接构造简单响应结果返回
        final String fromAlipayUserId = bizContent.getString("FromAlipayUserId");// 2088702468804908
        final String fromUserId = bizContent.getString("FromUserId");// 20880017371745854203313602619090
        System.out.println(fromAlipayUserId+"已关注服务!");
        //用户关注后，给用户发条消息
        try {
            // 2.1 构建一个业务响应消息，商户根据自行业务构建，这里只是一个简单的样例
            String requestMsg = AlipayMsgBuildUtil.buildSingleImgTextMsg(fromAlipayUserId);// 用fromUserId也可以发送消息

            AlipayClient alipayClient = AlipayAPIClientFactory.getAlipayClient();
            AlipayOpenPublicMessageCustomSendRequest request = new AlipayOpenPublicMessageCustomSendRequest();
            request.setBizContent(requestMsg);

            // 2.2 使用SDK接口类发送响应
            AlipayOpenPublicMessageCustomSendResponse response = alipayClient
                .execute(request);

            // 2.3 商户根据响应结果处理结果
            //这里只是简单的打印，请商户根据实际情况自行进行处理
            if (null != response && response.isSuccess()) {
                System.out.println("异步发送成功，结果为：" + response.getBody());
            } else {
                System.out.println("异步发送失败 code=" + response.getCode() + "msg："
                                   + response.getMsg());
            }
        } catch (Exception e) {
            System.out.println("异步发送失败");
        }
        
        return AlipayMsgBuildUtil.buildBaseAckMsg(fromUserId);
    }
}
